package com.exp.controller;

import com.baidu.aip.face.AipFace;
import com.exp.properties.FaceProperties;
import com.exp.properties.JwtProperties;
import com.exp.result.Result;
import com.exp.result.StatusCode;
import com.exp.service.UserInfService;
import com.exp.dto.LoginDTO;
import com.exp.pojo.UserInf;
import com.exp.utils.JwtUtil;
import com.exp.utils.Message;
import com.exp.vo.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录模块-why
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class LoginController {

    @Autowired
    private UserInfService userInfService;

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private FaceProperties faceProperties;


    /*
    * 用户登录1-账号和密码
    * 输入：用户名、密码
    * 密码加密
    * 使用jwt校验
    * */
//    @CrossOrigin(origins = "http://172.20.10.6:5173")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {

        System.out.println("登录开始："+loginDTO);
        UserInf userInf = userInfService.login(loginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userInf.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        LoginVO loginVO = LoginVO.builder()
                .id(userInf.getId())
                .username(userInf.getUsername())
                .loginname(userInf.getLoginname())
                .token(token)
                .build();
        System.out.println("登录结束");
        return Result.success(StatusCode.SUCCESS, Message.LOGIN_SUCCESS,loginVO);
    }


    @PostMapping("/faceLogin")
    public Result faceLogin(@RequestBody String base64ImageStr) throws Exception {
        log.info("人脸登录开启~~~~·");
        AipFace client = null;
        try {
            client = new AipFace(faceProperties.getAppId(), faceProperties.getApiKey(), faceProperties.getSecretKey());
            client.setConnectionTimeoutInMillis(5000); // 5秒
            client.setSocketTimeoutInMillis(60000); // 60秒

            HashMap<String, Object> options = new HashMap<>();
            options.put("match_threshold", "90");
            options.put("quality_control", "NORMAL");
            options.put("liveness_control", "LOW");
            options.put("max_user_num", "3");

            // 调用接口
            String image = base64ImageStr;
            String imageType = "BASE64";
            String groupIdList = "test";

            //去掉 data 头
            String base64String = image.split(",")[1];
            // 人脸搜索
            JSONObject res = client.search(base64String, imageType, groupIdList, options);
            System.out.println(res.toString(2));

            // 检查是否存在error_code，如果有错误则抛出异常
            int errorCode = res.optInt("error_code", 0); // 使用optInt获取error_code，如果不存在则默认为0
            if (errorCode != 0) {
                String errorMsg = res.optString("error_msg", "未知错误");
                throw new Exception("登录失败：" + errorMsg);
            }

            // 检查是否存在result和user_list
            JSONObject result = res.optJSONObject("result"); // 使用optJSONObject获取result，如果不存在则为null
            if (result != null && result.has("user_list")) {
                JSONArray user_list = result.getJSONArray("user_list");
                // 遍历user_list数组，获取第一个用户的user_id
                for (int i = 0; i < user_list.length(); i++) {
                    JSONObject user = user_list.getJSONObject(i);
                    if (user.has("user_id")) {
                        String user_id = user.getString("user_id");
                        // 这里可以处理user_id，例如打印或者返回
                        System.out.println("User ID: " + user_id);

                        Integer userId = Integer.valueOf(user_id);
                        Map<String, Object> claims = new HashMap<>();
                        claims.put("userId", userId); // 将user_id放入claims中
                        String token = JwtUtil.createJWT(
                                jwtProperties.getAdminSecretKey(),
                                jwtProperties.getAdminTtl(),
                                claims);

                        UserInf userInf = userInfService.getById(userId);
                        LoginVO loginVO = LoginVO.builder()
                                .id(userId)
                                .username(userInf.getUsername())
                                .loginname(userInf.getLoginname())
                                .token(token)
                                .build();

                        return Result.success(StatusCode.SUCCESS, Message.LOGIN_SUCCESS, loginVO);
                    }
                }
                // 如果user_list不为空，但是没有找到user_id，返回失败结果
                return Result.error(StatusCode.ERROR, Message.ACCOUNT_NOT_FOUND);
            } else {
                // 如果没有找到user_list，返回失败结果
                return Result.error(StatusCode.ERROR, Message.ACCOUNT_NOT_FOUND);
            }

        } catch (Exception e) {
            return Result.error(StatusCode.ERROR, Message.LOGIN_FAILED + e.getMessage());
        }
    }
}
